package com.fbinggun.playeraddattribute;

import com.alibaba.fastjson.JSONObject;
import com.fbinggun.fattribute.attribute.IAttribute;
import com.fbinggun.sql.Formula;
import com.fbinggun.sql.Table;


import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class AttributeTabel {
    Table table;

    public AttributeTabel() throws SQLException, ClassNotFoundException {
        table= new Table(PlayerAddAttribute.sql,"playerattribute");
        if(!table.IsTableNull()){
            table.CreateTable(
                    new Formula("Player", "VARCHAR", 50),
                    new Formula("Data", "text")
            );
        }
    }

    public Map<IAttribute,Double> getData(String json){
        Map<IAttribute,Double> map = new HashMap<>();
        if(json==null){
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(json);
        for(String key:jsonObject.getInnerMap().keySet()){
            IAttribute iAttribute=  IAttribute.getKey(key);
            if(iAttribute!=null){
                map.put(iAttribute,jsonObject.getDouble(key));
            }

        }
        return map;
    }

    public PlayerData getPlayerData(String player) throws SQLException, ClassNotFoundException {
        String json = getJson(player);
        if(json==null){
            return new PlayerData(player);
        }
        Map<IAttribute,Double> map =getData(getJson(player));
        if(map==null){
            return new PlayerData(player);
        }
        return new PlayerData(player,map);
    }

    private String getJson(String player) throws SQLException, ClassNotFoundException {
        Object o= table.getObject("Player",player,"Data");
        if(o==null){
            return null;
        }
        String json = (String) o;
        if(json.equalsIgnoreCase("")||json.equalsIgnoreCase("null")){
            return null;
        }
        return json;
    }
    public void setJson(PlayerData player) throws SQLException, ClassNotFoundException {
        table.setObject("Player",player.player,"Data",player.toJSONObject());
    }



}
